package com.cans.lightning;

import java.util.LinkedList;

/**
 * 多线程非阻塞队列
 *
 * @author cans
 * @date 2021-07-09 10:35
 **/
public class MyQueue {

    /**
     * 维护的队列
     */
    private final LinkedList<String> queue = new LinkedList<>();

    private int max = 10;

    /**
     * 插入到末尾
     *
     * @param code
     */
    public synchronized void putLast(String code) throws InterruptedException {

        Thread thread = Thread.currentThread();

        String threadName = thread.getName();

        while (queue.size() == max) {

            System.out.println("容器已满暂停入队---" + threadName);
            this.wait();
        }

        System.out.println("线程: " + threadName + "入队__" + code + "容量:" + queue.size());

        Thread.sleep(500);

        this.notify();

        queue.addLast(code);
    }


    /**
     * 获取第一位
     *
     * @return
     */
    public synchronized String getFirst() throws InterruptedException {

        String threadName = Thread.currentThread().getName();

        while (queue.size() == 0) {
            System.out.println("容器已空暂停出队---" + threadName);
            this.wait();
        }

        String first = queue.getFirst();

        queue.removeFirst();

        this.notify();

        return first;
    }

}



